package com.tanhua.sso.controller;

import cn.hutool.core.util.ObjectUtil;
import com.tanhua.common.pojo.Admin;
import com.tanhua.common.vo.AdminVo;
import com.tanhua.sso.service.RandomValidateCodeUtil;
import com.tanhua.sso.service.SystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("users")
@Slf4j
public class SystemLoginController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SystemService systemService;
    @Autowired
    private RandomValidateCodeUtil randomValidateCodeUtil;

    //用户登录
    @PostMapping("login")
    public ResponseEntity<Map<String , Object>> login1(@RequestBody AdminVo adminVo) {
        //封装一个实体类获取页面参数校验返回token
        Map<String, Object> token = systemService.queryToken(adminVo);
        return ResponseEntity.ok(token);
    }

    //用户基本信息
    @PostMapping("profile")
    public ResponseEntity profile(@RequestHeader("Authorization")String token) {
        Admin admin =  this.systemService.profile(token);
        if (ObjectUtil.isNotEmpty(admin)) {
            return ResponseEntity.ok(admin);
        }
        return ResponseEntity.ok(null);
    }

    //用户登录验证
    @GetMapping("verification")
    public void getVerification(@RequestParam String uuid, HttpServletResponse response) {
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        randomValidateCodeUtil.getRandcode(uuid,response); //输出验证码图片方法

        //return ResponseEntity.ok(randomValidateCodeUtil);
    }

    //用户登出
    @PostMapping("logout")
    public ResponseEntity logout(@RequestHeader("Authorization")String token) {
        systemService.delToken(token);
        return ResponseEntity.ok(null);
    }

    //解析token的接口
    @GetMapping("{token}")
    public Admin checkCode(@PathVariable("token") String token){
        //调用service方法解析token
        Admin admin = systemService.getToken(token);
        return admin;
    }

}